import 'package:hrf_app/common/api/bug/bug.dart';
import 'package:hrf_app/common/extension/ex_visibility.dart';
import 'package:hrf_app/common/models/bug/project_bug_model.dart';
import 'package:hrf_app/common/models/bug/project_user_model.dart';
import 'package:hrf_app/common/routers/names.dart';
import 'package:hrf_app/common/services/user.dart';
import 'package:hrf_app/common/values/svgs.dart';
import 'package:hrf_app/pages/menu/bug_page_list/projectBugPage/model/searchProjectBugModel.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';



class ProjectBugTabPage extends StatefulWidget {
  final String projectId;

  const ProjectBugTabPage({Key? key, required this.projectId})
      : super(key: key);

  @override
  State<ProjectBugTabPage> createState() => ProjectBugTabPageState();
}

class ProjectBugTabPageState extends State<ProjectBugTabPage> {
  late List<ProjectBugModel> projectBugList;

  @override
  void initState() {
    projectBugList = [];
    onInit();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return _buildView();
  }

  Widget _buildView() {
    return Column(
      children: [
        // _buildDownChunk(),
        Expanded(
            child: EasyRefresh(
          controller: easyRefreshController,
          onRefresh: () async {
            print("下拉刷新逻辑");
            onRefresh();
          },
          onLoad: () async {
            print("上拉加载逻辑");
            onLoad();
          },
          child: ListView.builder(
              itemCount: projectBugList.length,
              itemBuilder: (context, index) {
                ProjectBugModel projectBugModel = projectBugList[index];
                return _buildItemView(projectBugModel);
              }),
        ))
      ],
    );
  }

  // 主视图
  Widget _buildItemView(ProjectBugModel projectBugModel) {
    return Container(
        margin: const EdgeInsets.all(8),
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: const [BoxShadow(color: Colors.grey, blurRadius: 0.3)],
          borderRadius: BorderRadius.circular(10),
        ),
        child: SizedBox(height: 130, child: _buildBugInfo(projectBugModel)));
  }

  Widget _buildBugInfo(ProjectBugModel projectBugModel) {
    int? priority = projectBugModel.priority;
    int? status = projectBugModel.status;
    String? assignUserId = projectBugModel.assignUserId;
    String priorityName = "低";
    TDTagTheme tagThemePriority = TDTagTheme.primary;
    if (priority == 2) {
      priorityName = "中";
      tagThemePriority = TDTagTheme.warning;
    }
    if (priority == 3) {
      priorityName = "高";
      tagThemePriority = TDTagTheme.danger;
    }
    String statusName = "未完成";
    TDTagTheme tagThemeStatus = TDTagTheme.danger;
    if (status == 5) {
      statusName = "已暂停";
      tagThemeStatus = TDTagTheme.warning;
    }
    if (status == 10) {
      statusName = "已解决";
      tagThemeStatus = TDTagTheme.primary;
    }
    if (status == 20) {
      statusName = "已关闭";
      tagThemeStatus = TDTagTheme.success;
    }
    String userId = UserService.to.profile.id!;
    Color assignNameColor = Colors.black;
    if (assignUserId == userId) {
      assignNameColor = Colors.red;
    }
    List<Widget> columList = [];
    columList.add(buildInfoDetailTitle("标题：", projectBugModel.title!));
    columList.add(buildInfoDetailIDLeftRight(
        Row(
          children: [
            itemTitle(
              "ID：",
            ),
            TDText(projectBugModel.idSort.toString()),
          ],
        ),
        Row(
          children: [
            itemTitle(
              "状态：",
            ),
            TDTag(statusName, theme: tagThemeStatus),
          ],
        )));
    columList.add(buildInfoDetailIDLeftRight(
      Row(
        children: [
          itemTitle(
            "项目：",
          ),
          TDText(projectBugModel.projectName!),
        ],
      ),
      Row(
        children: [
          itemTitle(
            "指派人：",
          ),
          Row(
            children: [
              TDText(
                projectBugModel.assignUserName == null
                    ? ""
                    : projectBugModel.assignUserName,
                textColor: assignNameColor,
              ),
              const SizedBox(
                width: 3,
              ),
              InkWell(
                  onTap: () {
                    editAssignUserDialog(projectBugModel.assignUserName ?? "",
                        "assignUserName", "指派人", projectBugModel.id!);
                  },
                  child: SvgPicture.asset(
                    AssetsSvgs.pointRight, // 使用 SVG 图标
                    width: 18,
                    height: 18,
                    color: Colors.blueAccent,
                  )).toVisibility(visible: projectBugModel.status == 0)
            ],
          )
        ],
      ),
    ));

    columList.add(buildInfoDetailIDLeftRight(
        Row(
          children: [
            itemTitle(
              "创建人：",
            ),
            TDText(projectBugModel.creatorName!),
          ],
        ),
        Row(
          children: [
            itemTitle(
              "优先级：",
            ),
            TDTag(
              priorityName,
              theme: tagThemePriority,
              isOutline: true,
            ),
          ],
        )));

    columList.add(
      buildInfoDetailTitle(
        "创建时间：",
        projectBugModel.createTime!,
      ),
    );
    return InkWell(
        onTap: () {
          onJumpToDetail(projectBugModel.id);
        },
        child: Column(children: columList));
  }

//标题内容行
  Widget buildInfoDetailTitle(String title, String content) {
    return Row(
      children: [
        TDText(
          title,
          fontWeight: FontWeight.w700,
        ),
        Expanded(
          child: TDText(
            content,
            overflow: TextOverflow.ellipsis,
          ),
        )
      ],
    );
  }

//标题

  Widget buildInfoDetailIDLeftRight(Widget leftWidget, Widget rightWidget) {
    return Row(
      children: [
        Expanded(flex: 3, child: leftWidget),
        Expanded(flex: 3, child: rightWidget),
      ],
    );
  }

  Widget itemTitle(title) {
    return TDText(
      title,
      fontWeight: FontWeight.w700,
    );
  }

  SearchProjectBugModel searchProjectBugModel = SearchProjectBugModel();
  List<TDDropdownItemOption> userWidgetList = [];
  bool isLoading = false;
  late EasyRefreshController easyRefreshController;
  List<ProjectUserModel> projectUserList = [];

  _initData() {
    searchProjectBugModel.projectIdInList = [widget.projectId];
    getProjectBugListPage(searchProjectBugModel);
    getPjProjectUserList();
  }

  getPjProjectUserList() async {
    List<ProjectUserModel> userList = [];
    Map<String, dynamic> res = await BugApi.getPjProjectUserListApi({});
    for (var item in res["data"]) {
      userList.add(ProjectUserModel.fromJson(item));
    }
    projectUserList = userList;
  }

  getProjectBugListPage(params) {
    BugApi.getPjProjectBugPageListApi(params).then((res) {
      if (res["code"] == "00000") {
        List<ProjectBugModel> projectBugDetailList = [];
        for (var item in res["data"]["records"]) {
          projectBugDetailList.add(ProjectBugModel.fromJson(item));
        }

        setState(() {
          projectBugList = projectBugDetailList;
        });
      }
    });
  }

  onJumpToDetail(id) {
    Get.toNamed(RouteNames.projectBugDetailPage, arguments: id);
  }

  void onInit() {
    easyRefreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    _initData();
  }

  void editAssignUserDialog(
      String content, String filedName, String title, String id) async {
    Picker picket = Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: projectUserList.map((item) => item.realName).toList()),
        hideHeader: true);
    BuildContext? buildContext = Get.context!;
    Navigator.of(buildContext).push(TDSlidePopupRoute(
        slideTransitionFrom: SlideTransitionFrom.bottom,
        builder: (buildContext) {
          return TDPopupBottomConfirmPanel(
              title: "指派人 ",
              leftClick: () {
                Navigator.maybePop(buildContext);
              },
              rightClick: () {
                List<dynamic> value = picket.getSelectedValues();
                List<int> index = picket.selecteds;
                if (value.isEmpty) return;
                ProjectUserModel projectUserModel = projectUserList[index[0]];
                String userId = projectUserModel.userId!;
                updateUser(userId, id);
                Navigator.maybePop(buildContext);
              },
              child: picket.makePicker());
        }));
  }

  //修改指派人
  updateUser(String userId, String id) async {
    Map map = Map();
    map['assignUserId'] = userId;
    map['id'] = id;
    Map<String, dynamic> res =
        await BugApi.updatePjProjectBugAssignUserIdApi(map);
    if (res["code"] == "00000") {
      TDToast.showText('修改成功', context: Get.context!);
      getProjectBugListPage(searchProjectBugModel);
    }
  }

  void onRefresh() {
    searchProjectBugModel.pageNum = 1;
    BugApi.getPjProjectBugPageListApi(searchProjectBugModel).then((res) {
      if (res["code"] == "00000") {
        List<ProjectBugModel> projectBugDetailList = [];
        for (var item in res["data"]["records"]) {
          projectBugDetailList.add(ProjectBugModel.fromJson(item));
        }

        setState(() {
          projectBugList = projectBugDetailList;
        });
        easyRefreshController.finishRefresh(IndicatorResult.success);
        easyRefreshController.resetFooter();
      }
    });
  }

  void onLoad() {
    searchProjectBugModel.pageNum = searchProjectBugModel.pageNum + 1;
    BugApi.getPjProjectBugPageListApi(searchProjectBugModel).then((res) {
      if (res["code"] == "00000") {
        List<dynamic> projectBugResList = [];
        projectBugResList = res["data"]["records"];
        if (projectBugResList.isEmpty) {
          easyRefreshController.finishLoad(IndicatorResult.noMore);
          searchProjectBugModel.pageNum--;
        }
        if (projectBugResList.isNotEmpty) {
          List<ProjectBugModel> projectBugDetailList = projectBugList;
          for (var item in projectBugResList) {
            projectBugDetailList.add(ProjectBugModel.fromJson(item));
          }
          setState(() {
            projectBugList = projectBugDetailList;
          });
          easyRefreshController.finishLoad();
        }
      }
    });
  }

  void statusOnReset() {
    searchProjectBugModel.pageNum = 1;
    searchProjectBugModel.statusInList = [];
    getProjectBugListPage(searchProjectBugModel);
  }

  void userOnChange(val) {
    easyRefreshController.resetFooter();
    searchProjectBugModel.pageNum = 1;
    searchProjectBugModel.userIdInList = val;
    setState(() {
      projectBugList = [];
    });
    getProjectBugListPage(searchProjectBugModel);
  }

  void userOnReset() {
    searchProjectBugModel.pageNum = 1;
    searchProjectBugModel.userIdInList = [];
    getProjectBugListPage(searchProjectBugModel);
  }

  void statusOnChange(val) {
    easyRefreshController.resetFooter();
    searchProjectBugModel.pageNum = 1;
    searchProjectBugModel.statusInList = val;
    setState(() {
      projectBugList = [];
    });
    getProjectBugListPage(searchProjectBugModel);
  }

  void projectOnReset() {
    searchProjectBugModel.pageNum = 1;
    searchProjectBugModel.projectIdInList = [];
    getProjectBugListPage(searchProjectBugModel);
  }
}
